package com.example.test

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.SavedStateHandle
import kotlin.math.log

/**
 *@author : Administrator
 *@descreption : ViewModle加LiveData
 */
class ViewModelWithLiveData(var saveStateHandle: SavedStateHandle) : ViewModel() {
 private var person: MutableLiveData<Person>? = null
    get() {
        if (field ==null){  //field 代表person,在get和set中操作的对象要用field来代替,不然会无线循环而奔溃
            field  = MutableLiveData<Person>()
            var p:Person? = Person("ppp",90)
            if (saveStateHandle.contains("person")){
                Log.i("TAG", "saveStateHandle有值 ${saveStateHandle.get<Person>("person")} ");
                p = saveStateHandle.get("person")
            }
            field !!.value = p
            saveStateHandle.set("person",p)
        }
    return field
    }
    //对外访问person的方法
    fun getData(): MutableLiveData<Person>? {
        return  person
    }
    //加1操作
    fun addAge() {
        val data = this.person?.value ?: return
        data.age += 1
        this.person?.value = data
        saveStateHandle.set("person",data)

    }
    //减1操作
    fun subAge() {
        val data = this.person?.value ?: return
        data.age -= 1
        this.person?.value = data
        saveStateHandle.set("person",data)
    }
}